package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 根据id查询blog
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {
        // 1.查询blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在！");
        }
        // 2.查询blog有关的用户
        queryBlogUser(blog);

        // 3.查询当前登录用户是否已点赞过该推文
        queryIsLiked(blog);

        return Result.ok(blog);
    }

    /**
     * 分页查询推文
     * @param current
     * @return
     */
    @Override
    public Result queryHotBlog(Integer current) {
                // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            queryBlogUser(blog);
            queryIsLiked(blog);
        });
        return Result.ok(records);
    }

    /**
     * 当前用户点赞推文
     * @param id
     * @return
     */
    @Override
    public Result likeBlogById(Long id) {
        // 获取当前用户
        UserDTO user = UserHolder.getUser();

        String key = RedisConstants.BLOG_LIKED_KEY + id;

        // 判断当前用户是否点过赞（redis中会存放以blogId为key，userid为value，当前时间戳为score的zset集合）
        Double score = stringRedisTemplate.opsForZSet().score(key, user.getId().toString());
        // 如果没有点过赞
        if (score == null){
            // 数据库中点赞数+1
            boolean isSuccess = this.update().setSql("liked = liked + 1").eq("id", id).update();

            // 将当前用户id添加到redis的set集合中
            if (isSuccess){
                stringRedisTemplate.opsForZSet().add(key, user.getId().toString(), System.currentTimeMillis());
            }

        }else {
            // 如果点过赞
            // 数据库中点赞数 - 1
            boolean isSuccess = this.update().setSql("liked = liked - 1").eq("id", id).update();

            // 将当前用户id从redis的set集合中移除
            if (isSuccess){
                stringRedisTemplate.opsForZSet().remove(key, user.getId().toString());
            }

        }

        return Result.ok();
    }

    /**
     * 根据推文id查询最早点赞的前五名用户
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Set<String> range = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (range == null || range.isEmpty()){
            return Result.ok(Collections.EMPTY_LIST);
        }
        List<Long> userIds = range.stream().map(Long::valueOf).collect(Collectors.toList());

        String idStr = StrUtil.join(",", userIds);
        // 3.根据用户id查询用户 WHERE id IN ( 5 , 1 ) ORDER BY FIELD(id, 5, 1)
        List<UserDTO> userDTOS = userService.query()
                .in("id", userIds).last("ORDER BY FIELD(id," + idStr + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 4.返回
        return Result.ok(userDTOS);
    }

    /**
     * 查询发布该blog的user
     * @param blog
     */
    private void queryBlogUser(Blog blog) {
        User user = userMapper.selectById(blog.getUserId());
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    /**
     * 查询当前用户是否已经点赞过该推文
     * @param blog
     */
    private void queryIsLiked(Blog blog) {
        // 获取当前用户
        UserDTO user = UserHolder.getUser();
        if (user == null){
            return;
        }

        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();

        // 判断当前用户是否点过赞（redis中会存放以blogId为key，userid为value，当前时间戳为score的zset集合）
        Double score = stringRedisTemplate.opsForZSet().score(key, user.getId().toString());
        if (score == null){
            blog.setIsLike(false);
        }else {
            blog.setIsLike(true);
        }
    }
}
